package team.nmsg.visualchassis.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import team.nmsg.ge.system.controller.BaseController;
import team.nmsg.visualchassis.service.IVisualChassisService;

@RestController
@RequestMapping("chassis")
public class VisualChassisController extends BaseController{
	private static final Logger logger = LoggerFactory.getLogger(VisualChassisController.class);
	
	@Autowired
	IVisualChassisService chassisService = null;
	
	@RequiresPermissions("chassistest")
	@RequestMapping("/test")
	public String permissionTest(HttpServletRequest request , HttpServletResponse response){
		logger.debug("testestestestestestest");
		try {
			response.getWriter().write("testprint");
		} catch (Exception e) {
		}
		return null;
	}
	@RequiresPermissions("generateChassisProp")
	@RequestMapping("/createChassis")
	public String createChassis(HttpServletRequest request , HttpServletResponse response){
		JSONObject retObj = new JSONObject();
		try {
			String chassisJson = request.getParameter("chassis");
			
			Map<String, String> result = chassisService.createChassis(JSONObject.parseObject(chassisJson));
			retObj.put("result", result);
			
		} catch (Exception e) {
			logger.error("", e);
		}
		writeJson(retObj, response);
		return null;
	}
	@RequestMapping("/downloadFile")
	public String downloadFile(HttpServletRequest request , HttpServletResponse response){
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		FileInputStream fis = null;
		PrintWriter pw = null;
		try {
			String path = request.getParameter("path");
			File file = new File(path);
			fis = new FileInputStream(file);
			byte[] b = new byte[1024];
			int len = -1;
			while((len = fis.read(b)) != -1) {
			    bos.write(b, 0, len);
			}
			pw = response.getWriter();
			pw.print(bos);
			pw.flush();
			
		} catch (Exception e) {
			logger.error("", e);
		}finally{
			try {
				fis.close();
				pw.close();
			} catch (IOException e) {
				logger.error("", e);
			}
		}
		return null;
	}
}









